package com.tcl.aota.admin.job;

import com.tcl.aota.admin.dto.FileDTO;
import com.tcl.aota.common.constants.Constants;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * timing del the file from s3,upload apk,icon,imgs but don't submit the form to add a app.
 *
 * @author kelong
 * @date 11/21/14
 */
public class UpFileInstance {
    Logger LOG = Logger.getLogger(UpFileInstance.class);
    private static UpFileInstance instance;

    private static Map<String, String> fileUpLogCacheMap = new HashMap<String, String>();

    public Object lock = new Object();

    private UpFileInstance() {
    }

    /**
     * get a singeton
     *
     * @return
     */
    public static UpFileInstance getInstance() {
        if (instance == null) {
            synchronized (UpFileInstance.class) {
                if (instance == null) {
                    instance = new UpFileInstance();
                }
            }
        }
        return instance;
    }

    /**
     * put keys to cache when sync upload to s3
     *
     * @param key
     */
    public void put(String key) {
        synchronized (lock) {
            fileUpLogCacheMap.put(key, System.currentTimeMillis() + "");
        }
    }

    /**
     * remove keys when it is success to insert app
     *
     * @param keys
     */
    public void remove(List<String> keys) {
        synchronized (lock) {
            for (String key : keys) {
                fileUpLogCacheMap.remove(key);
            }
        }
    }

    public int getSize() {
        return fileUpLogCacheMap.size();
    }

    /**
     * clear the trash from s3
     *
     * @return
     */
    public int clearExpired() {
        int expireCount = 0;
        try {
            synchronized (lock) {
                long currentTimeMillis = System.currentTimeMillis();
                List<String> clearPathList = new ArrayList<String>();
                for (Map.Entry<String, String> entry : fileUpLogCacheMap.entrySet()) {
                    String descPath = entry.getKey();
                    long logTimeMillis = Long.parseLong(entry.getValue());
                    if (currentTimeMillis - logTimeMillis > Constants.Common.INTERVAL_TIME) {
                        clearPathList.add(descPath);//del file
                    }
                }
                for (String path : clearPathList) {
                    //del file from s3
                    FileDTO fileDTO = new FileDTO();
                    fileDTO.setFlag(Constants.AMAZON.DELETE_FLAG);
                    fileDTO.setDescPath(path);
                    StoreFilePool.getThreadPool().add(fileDTO);
                    //从map中把记录删掉
                    fileUpLogCacheMap.remove(path);
                    expireCount++;
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return expireCount;
    }
}
